package UDPProgramming.example01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author lhn
 * @date 2024-04-25 22:19
 * UDP发送端
 */

public class UDPReceiverB {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(9998);
        byte[] data = "hello, 明天吃火锅~".getBytes();
        /*
        * data -> 内容
        * data.length -> 内容长度
        * InetAddress.getByName("192.168.123.86") -> 主机地址
        * 9999 -> 端口
        */
        DatagramPacket datagramPacket = new DatagramPacket(
                data,
                data.length,
                InetAddress.getByName("192.168.123.86"),
                9999);
        datagramSocket.send(datagramPacket);
        System.out.println("发送完成");

        datagramSocket.receive(datagramPacket);
        int length = datagramPacket.getLength();
        byte[] receiveData = datagramPacket.getData();
        System.out.println("B端收到消息--" + new String(receiveData, 0, length));

        //关闭资源
        datagramSocket.close();
        System.out.println("B端关闭");
    }
}
